<template>
    <div>
        <!-- <searchForm :searchArr="searchArr" @onSubmit="onSubmit">
            <template #sbuName="{ item }">
                <el-select
                    v-model="item.value"
                    placeholder="请选择"
                    style="width: 100%"
                    :clearable="true"
                    filterable
                    remote
                    :remote-method="getSbuData"
                >
                    <el-option
                        v-for="item in sbuOptions"
                        :key="item.sbuName"
                        :label="item.sbuName"
                        :value="item.sbuName"
                    />
                </el-select>
            </template>
        </searchForm> -->
        <div class="gva-table-box">
            <div class="role">
                <LTable
                    tableName="subProjects"
                    :columns="columns"
                    :tableData="tableData"
                    :pages="pages"
                    @updateMultipleSelection="handleSelectionChange"
                    @changePages="changePages"
                    :typeItem="'projectColumns'"
                    :maxHeight="'calc(100vh - 226px)'"
                    :searchArr="searchArr"
                    :isSearch="true"
                    @onSubmit="onSubmit"
                    @rowDblclick="
                        (v) => {
                            getDetails(v, 'v');
                        }
                    "
                    :export="true"
                >
                    <!-- <template #projectNum="scope">
                        <el-popover
                            placement="right"
                            :width="80"
                            trigger="hover"
                        >
                            <template #reference>
                                {{ scope.row.projectNum }}
                            </template>
                            <div class="m-action-btns">
                                <el-button
                                    type="primary"
                                    link
                                    icon="edit"
                                    class="table-button"
                                    @click="getDetails(scope.row)"
                                    >编辑</el-button
                                >
                                <el-button
                                    type="primary"
                                    link
                                    icon="delete"
                                    @click="deleteRow(scope.row)"
                                    >删除</el-button
                                >
                                <relatedBtn
                                    :row="scope.row"
                                    :modalType="'project'"
                                />
                                <el-button
                                    type="primary"
                                    link
                                    icon="DocumentAdd"
                                    @click="createStyle(scope.row)"
                                    >创建款式</el-button
                                >
                            </div>
                        </el-popover>
                    </template> -->
                    <template #CreatedAt="{ row }">
                        {{ formatDate(row.CreatedAt) }}
                    </template>
                    <template #UpdatedAt="{ row }">
                        {{ formatDate(row.UpdatedAt) }}
                    </template>
                    <template #action>
                        <div class="gva-btn-list" v-if="userStore.userInfo.authority?.authorityId !== 1000">
                            <el-button
                                type="primary"
                                icon="plus"
                                @click="openCreateAndEdit"
                                >新增</el-button
                            >
                            <el-button
                                icon="delete"
                                style="margin-left: 10px"
                                v-auth="btnAuth.batchDel"
                                :disabled="!multipleSelection.length"
                                @click="onDelete"
                                >删除</el-button
                            >
                            <!-- <el-button
                                :disabled="multipleSelection.length!=1"
                                type="primary"
                                icon="edit"
                                class="table-button"
                                @click="getDetails(multipleSelection.length==1&&multipleSelection[0])"
                            >
                                编辑
                            </el-button> -->
                            <el-button
                                type="primary"
                                icon="DocumentAdd"
                                :disabled="multipleSelection.length!=1"
                                @click="createStyle(multipleSelection.length==1&&multipleSelection[0])"
                                >创建款式</el-button
                            >
                            <relatedBtn
                                :disabled="multipleSelection.length!=1"
                                :row="multipleSelection.length==1&&multipleSelection[0]"
                                :modalType="'project'"
                            />
                        </div>
                        <div v-else class="gva-btn-list" style="height:22px"></div>
                    </template>
                    <!-- <template #event>
                        <el-table-column
                            align="left"
                            label="操作"
                            fixed="right"
                            min-width="320"
                            width="320"
                        >
                            <template #default="scope">
                                <el-button
                                    type="primary"
                                    link
                                    icon="edit"
                                    class="table-button"
                                    @click="getDetails(scope.row)"
                                    >编辑</el-button
                                >
                                <el-button
                                    type="primary"
                                    link
                                    icon="delete"
                                    @click="deleteRow(scope.row)"
                                    >删除</el-button
                                >
                                <relatedBtn
                                    :row="scope.row"
                                    :modalType="'project'"
                                />
                                <el-button
                                    type="primary"
                                    link
                                    icon="DocumentAdd"
                                    @click="createStyle(scope.row)"
                                    >创建款式</el-button
                                >
                            </template>
                        </el-table-column>
                    </template> -->
                </LTable>
            </div>
        </div>
        <!-- 创建款式 -->
        <el-dialog
            v-model="createStyleDialogShow"
            destroy-on-close
            title="创建款式"
            width="450"
        >
            <div>
                创建款式数量：<el-input-number
                    v-model="createStyleNum"
                    :min="1"
                />
            </div>
            <template #footer>
                <div class="dialog-footer">
                    <el-button
                        type="primary"
                        @click="createSbuProjectsNumFun"
                        :loading="createStyleDialogShowLoading"
                        >确定</el-button
                    >
                    <el-button @click="createStyleDialogShow = false">
                        关闭
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { useRoute, useRouter } from "vue-router";
import {
    createSbuProjects,
    deleteSbuProjects,
    deleteSbuProjectsByIds,
    updateSbuProjects,
    findSbuProjects,
    getSbuProjectsList,
    createSbuProjectsNum,
} from "@/api/plmSbuProjects";
import { getSbuDataList } from "@/api/confSbuData";

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate } from "@/utils/format";
import { ElMessage, ElMessageBox } from "element-plus";
import { ref, reactive, computed, watch } from "vue";
// 引入组件
import LTable from "@/components/LTable/LTable.vue";
// import searchForm from "@/components/searchForm/searchForm.vue";
import { useI18n } from "vue-i18n";

const { t: il8n } = useI18n();
import { useBtnAuth } from "@/utils/btnAuth";
const btnAuth = useBtnAuth();
import { useUserStore } from '@/pinia/modules/user'
const userStore = useUserStore()
// console.log("userStore",userStore.userInfo.authority)

defineOptions({
    name: "SbuProjects",
});

// 使用 useRoute 函数获取当前路由信息
const route = useRoute();
// 使用 useRoute 函数获取当前路由信息
const router = useRouter();

// 自动化生成的字典（可能为空）以及字段
const sbuTypesOptions = ref([]);

// 验证规则
const rule = reactive({});

const elSearchFormRef = ref();

// =========== 表格控制部分 ===========
const tableData = ref([]);
const pages = ref({
    page: 1,
    pageSize: 20,
    total: 0,
});
const searchInfo = ref({});

const createStyleDialogShow = ref(false); // 创建款式弹窗
const createStyleDialogShowLoading = ref(false); // 创建款式弹窗
const createStyleNum = ref(1); // 创建款式数量
const currentItem = ref({}); // 当前点击节点

// ======表格头部数据======
const columns = ref([
    {
        prop: "projectNum",
        // width: 100,
        // fixedWidth:130,
        label: "项目编号",
        show: true, // 通过 show 来控制列的展示或隐藏
        filter: true,
        isSearch:true,
        // slot: "projectNum",
        tableColumnProps: {
            fixed: "left",
        },
    },
    {
        prop: "sbuName",
        // fixedWidth: 100,
        label: "SBU",
        filter: true,
        isSearch:true,
        show: true,
        value: undefined,
        type: "select",
        selectList: [],
    },
    {
        prop: "customerName",
        // fixedWidth: 120,
        label: "客户编号",
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "brandName",
        // fixedWidth: 130,
        label: "品牌",
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "CreatedAt",
        label: "创建时间",
        // fixedWidth: 130,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "createUser",
        label: "创建人",
        // fixedWidth: 100,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "UpdatedAt",
        label: "更新时间",
        // fixedWidth: 130,
        show: true,
        filter: true,
        isSearch:true,
    },
    {
        prop: "updateUser",
        label: "更新人",
        // fixedWidth: 100,
        show: true,
        filter: true,
        isSearch:true,
    },
]);
// ======查询数据======
const searchArr = ref([
    {
        prop: "projectNum",
        label: "项目编号",
        show: true, // 通过 show 来控制列的展示或隐藏
        value: "",
        type: "input",
    },
    {
        prop: "sbuName",
        label: "SBU",
        show: true,
        value: "",
        type: "input",
        slot: "sbuName",
    },
    {
        prop: "customerName",
        label: "客户编号",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "brandName",
        label: "品牌",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "CreatedAt",
        label: "创建时间",
        show: true,
        value: "",
        type: "datetimerange",
    },
    {
        prop: "createUser",
        label: "创建人",
        show: true,
        value: "",
        type: "input",
    },
    {
        prop: "UpdatedAt",
        label: "更新时间",
        show: true,
        value: "",
        type: "datetimerange",
    },
    {
        prop: "updateUser",
        label: "更新人",
        show: true,
        value: "",
        type: "input",
    },
]);

// 重置
const onReset = () => {
    searchInfo.value = {};
    getTableData();
};

// 搜索
const onSubmit = (val) => {
    searchInfo.value = {
        ...val,
    };
    // if (searchInfo.value.CreatedAt) {
    //     searchInfo.value["startCreatedAt"] =
    //         searchInfo.value.CreatedAt[0] || "";
    //     searchInfo.value["endCreatedAt"] = searchInfo.value.CreatedAt[1] || "";
    // }
    // if (searchInfo.value.UpdatedAt) {
    //     searchInfo.value["startUpdatedAt"] =
    //         searchInfo.value.UpdatedAt[0] || "";
    //     searchInfo.value["endUpdatedAt"] = searchInfo.value.UpdatedAt[1] || "";
    // }
    pages.value.page = 1;
    pages.value.pageSize = 20;
    getTableData();
};

// 改变页码
const changePages = (currentPages) => {
    pages.value = {
        ...pages.value,
        ...currentPages,
    };
    getTableData();
};

// 查询
const getTableData = async () => {
    const table = await getSbuProjectsList({
        page: pages.value.page,
        pageSize: pages.value.pageSize,
        ...searchInfo.value,
    });
    if (table.code === 0) {
        tableData.value = table.data.list.map((item) => {
            item.CreatedAt = item.CreatedAt ? formatDate(item.CreatedAt) : "";
            item.UpdatedAt = item.UpdatedAt ? formatDate(item.UpdatedAt) : "";
            return item;
        });
        pages.value.total = table.data.total;
        pages.value.page = table.data.page;
        pages.value.pageSize = table.data.pageSize;
    }
};

// getTableData();

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () => {
    sbuTypesOptions.value = await getDictFunc("sbuTypes");
};

// 获取需要的字典 可能为空 按需保留
setOptions();

// 多选数据
const multipleSelection = ref([]);
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val;
};

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        deleteSbuProjectsFunc(row);
    });
};

// 多选删除
const onDelete = async () => {
    ElMessageBox.confirm("确定要删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(async () => {
        const IDs = [];
        if (multipleSelection.value.length === 0) {
            ElMessage({
                type: "warning",
                message: "请选择要删除的数据",
            });
            return;
        }
        multipleSelection.value &&
            multipleSelection.value.map((item) => {
                IDs.push(item.ID);
            });
        const res = await deleteSbuProjectsByIds({ IDs });
        if (res.code === 0) {
            ElMessage({
                type: "success",
                message: "删除成功",
            });
            if (tableData.value.length === IDs.length && pages.value.page > 1) {
                pages.value.page--;
            }
            getTableData();
        }
    });
};

// 行为控制标记（弹窗内部需要增还是改）
const type = ref("");

// 删除行
const deleteSbuProjectsFunc = async (row) => {
    const res = await deleteSbuProjects({ ID: row.ID });
    if (res.code === 0) {
        ElMessage({
            type: "success",
            message: "删除成功",
        });
        if (tableData.value.length === 1 && pages.value.page > 1) {
            pages.value.page--;
        }
        getTableData();
    }
};

// 打开 新增、修改
const openCreateAndEdit = () => {
    type.value = "create";
    router.push({
        path: "/layout/plmSbuProjectsAdd",
    });
};

// 打开详情
const getDetails = async (row, action) => {
    router.push({
        path: "/layout/plmSbuProjectsView",
        query: {
            id: row.ID,
            action,
            subTitle:row.projectNum
        },
    });
};

// 创建款式
const createStyle = (item) => {
    createStyleDialogShow.value = true;
    createStyleNum.value = 1;
    currentItem.value = item;
};

// 创建款式
const createSbuProjectsNumFun = () => {
    let params = {
        ID: currentItem.value.ID + "",
        total: createStyleNum.value,
    };
    createStyleDialogShowLoading.value = true;
    createSbuProjectsNum(params)
        .then((res) => {
            createStyleDialogShow.value = false;
            createStyleDialogShowLoading.value = false;
            if (res.code == 0) {
                ElMessage({
                    type: "warning",
                    message: "创建成功",
                });
            }
        })
        .catch((err) => {
            createStyleDialogShow.value = false;
            createStyleDialogShowLoading.value = false;
        });
};

// sub列表
const sbuOptions = ref([]);
// 获取sbu列表
const getSbuData = async (keyword) => {
    await getSbuDataList({ page: 1, pageSize: 100, sbuName: keyword }).then(
        (res) => {
            if (res.code === 0) {
                sbuOptions.value = res.data.list;
            }
        }
    );
};

watch(() => route.path, (newPath, oldPath) => {
//   console.log('路由已变更：', `从 ${oldPath} 到 ${newPath}`);
    if(newPath == '/layout/sbuProjects'){
        getTableData();
    }
},{immediate:true});

</script>

<style lang="scss" scoped>
@import url("@/style/common/common.scss");
</style>
